/*
 * Copyright 2002-2017 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.beans.factory.xml;

import java.io.IOException;
import java.net.URISyntaxException;
import java.util.LinkedHashSet;
import java.util.Set;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import org.springframework.beans.factory.BeanDefinitionStoreException;
import org.springframework.beans.factory.config.BeanDefinitionHolder;
import org.springframework.beans.factory.parsing.BeanComponentDefinition;
import org.springframework.beans.factory.support.BeanDefinitionReaderUtils;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.ResourcePatternUtils;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.util.ResourceUtils;
import org.springframework.util.StringUtils;

/**
 * BeanDefinitionDocumentReader的默认实现,实现了根据DTX和XSD格式读取bean定义.
 * 像结构,元素和属性名称都会硬编码在当前类中(如果需要的话,可以用工具生成XML文档).
 * 对于XML文档来说,Beans节点不需要一定是跟节点.当前类会解析XMl中所有的bean定义元素,而不去在意真正意义上的跟节点.
 * <p>
 * <p>
 * Default implementation of the {@link BeanDefinitionDocumentReader} interface that
 * reads bean definitions according to the "spring-beans" DTD and XSD format
 * (Spring's default XML bean definition format).
 * <p>
 * <p>The structure, elements, and attribute names of the required XML document
 * are hard-coded in this class. (Of course a transform could be run if necessary
 * to produce this format). {@code <beans>} does not need to be the root
 * element of the XML document: this class will parse all bean definition elements
 * in the XML file, regardless of the actual root element.
 *
 * @author Rod Johnson
 * @author Juergen Hoeller
 * @author Rob Harrop
 * @author Erik Wiersma
 * @since 18.12.2003
 */
public class DefaultBeanDefinitionDocumentReader implements BeanDefinitionDocumentReader {
	/**
	 * Bean元素
	 */
	public static final String BEAN_ELEMENT = BeanDefinitionParserDelegate.BEAN_ELEMENT;
	/**
	 * 嵌入的Bean元素
	 */
	public static final String NESTED_BEANS_ELEMENT = "beans";
	/**
	 * 别名元素
	 */
	public static final String ALIAS_ELEMENT = "alias";
	/**
	 * 属性名
	 */
	public static final String NAME_ATTRIBUTE = "name";
	/**
	 * 别名属性
	 */
	public static final String ALIAS_ATTRIBUTE = "alias";
	/**
	 * 引入元素
	 */
	public static final String IMPORT_ELEMENT = "import";
	/**
	 * 资源文件元素
	 */
	public static final String RESOURCE_ATTRIBUTE = "resource";
	/**
	 * 配置文件元素
	 */
	public static final String PROFILE_ATTRIBUTE = "profile";


	protected final Log logger = LogFactory.getLog(getClass());
	/**
	 * 读取XML文件的上下文类
	 */
	@Nullable
	private XmlReaderContext readerContext;
	/**
	 * 解析XML Bean定义的有状态委托类.
	 */
	@Nullable
	private BeanDefinitionParserDelegate delegate;


	/**
	 * 根据spring-beans的XSD或者DTD定义来解析Bean定义.
	 * 打开一个DOM文档,然后根据beans标签中的内容进行初始化设置,然后解析其中包含的bean定义.
	 * <p>
	 * <p>
	 * This implementation parses bean definitions according to the "spring-beans" XSD
	 * (or DTD, historically).
	 * <p>Opens a DOM Document; then initializes the default settings
	 * specified at the {@code <beans/>} level; then parses the contained bean definitions.
	 */
	@Override
	public void registerBeanDefinitions(Document doc, XmlReaderContext readerContext) {
		//指定解析文档过程中的上下文处理类.
		this.readerContext = readerContext;
		logger.debug("Loading bean definitions");
		/**
		 * 获取文档中的根元素,然后开始执行解析和注册操作.
		 */
		Element root = doc.getDocumentElement();
		doRegisterBeanDefinitions(root);
	}

	/**
	 * Return the descriptor for the XML resource that this parser works on.
	 */
	protected final XmlReaderContext getReaderContext() {
		Assert.state(this.readerContext != null, "No XmlReaderContext available");
		return this.readerContext;
	}

	/**
	 * Invoke the {@link org.springframework.beans.factory.parsing.SourceExtractor}
	 * to pull the source metadata from the supplied {@link Element}.
	 */
	@Nullable
	protected Object extractSource(Element ele) {
		return getReaderContext().extractSource(ele);
	}


	/**
	 * 注册给定跟节点中的每一个元素定义.
	 * Register each bean definition within the given root {@code <beans/>} element.
	 */
	protected void doRegisterBeanDefinitions(Element root) {
		//当前方法会递归处理所有的嵌套的<beans>元素,为了正确传播和保存<beans>的default-*属性,
		// 将会保持跟踪当前(其父类)的状态委托行为,它可以为null.
		// 为了让父类的状态委托为推到原始的情况,创建一个新的状态委托类对其引用,最终重置当前的状态委托类成为最原始的引用.
		//这种行为模拟了一堆委托而不是只存在一个委托.

		// Any nested <beans> elements will cause recursion in this method. In
		// order to propagate and preserve <beans> default-* attributes correctly,
		// keep track of the current (parent) delegate, which may be null. Create
		// the new (child) delegate with a reference to the parent for fallback purposes,
		// then ultimately reset this.delegate back to its original (parent) reference.
		// this behavior emulates a stack of delegates without actually necessitating one.
		//声明一个窗台委托类为当前持有的状态委托类.
		BeanDefinitionParserDelegate parent = this.delegate;
		//通过当前的XML上下文处理类,跟节点,以及当前的状态委托类,重新初始化当前的状态委托类.
		//其目的就是合并所有的状态委托类
		this.delegate = createDelegate(getReaderContext(), root, parent);
		//判断当前是不是使用默认的命名空间
		if (this.delegate.isDefaultNamespace(root)) {
			//处理profile文件,针对不同的环境加载不同的配置文件.
			String profileSpec = root.getAttribute(PROFILE_ATTRIBUTE);
			if (StringUtils.hasText(profileSpec)) {
				//包含了该属性,通过分隔符解析出所有的配置文件
				String[] specifiedProfiles = StringUtils.tokenizeToStringArray(
						profileSpec, BeanDefinitionParserDelegate.MULTI_VALUE_ATTRIBUTE_DELIMITERS);
				if (!getReaderContext().getEnvironment().acceptsProfiles(specifiedProfiles)) {
					if (logger.isInfoEnabled()) {
						logger.info("Skipped XML bean definition file due to specified profiles [" + profileSpec +
								"] not matching: " + getReaderContext().getResource());
					}
					return;
				}
			}
		}
		//前置后置处理是标准的模板模式
		//装载bean前置处理
		preProcessXml(root);
		//解析并并注册bean.
		parseBeanDefinitions(root, this.delegate);
		//装载bean后处理
		postProcessXml(root);

		this.delegate = parent;
	}

	protected BeanDefinitionParserDelegate createDelegate(
			XmlReaderContext readerContext, Element root, @Nullable BeanDefinitionParserDelegate parentDelegate) {
		/**
		 * 用传入的上下文,来初始化一个新的状态委托类.
		 */
		BeanDefinitionParserDelegate delegate = new BeanDefinitionParserDelegate(readerContext);
		delegate.initDefaults(root, parentDelegate);
		return delegate;
	}

	/**
	 * 解析当前文档中根元素级别的元素:import,alias,bean.
	 * <p>
	 * <p>
	 * Parse the elements at the root level in the document:
	 * "import", "alias", "bean".
	 *
	 * @param root the DOM root element of the document
	 */
	protected void parseBeanDefinitions(Element root, BeanDefinitionParserDelegate delegate) {
		//如果当前跟节点包含了nameSpaceUri,且声明和BEANS_NAMESPACE_URI参数一致,表明是使用的默认的命名空间.
		// 默认命名空间的值:[http://www.springframework.org/schema/beans]
		if (delegate.isDefaultNamespace(root)) {
			//解析默认的命名空间
			NodeList nl = root.getChildNodes();//获取根元素级别的所有元素定义
			for (int i = 0; i < nl.getLength(); i++) {
				Node node = nl.item(i);
				if (node instanceof Element) {
					//首先要求获取到的节点是个元素
					Element ele = (Element) node;
					if (delegate.isDefaultNamespace(ele)) {
						//解析默认的命名空间元素
						parseDefaultElement(ele, delegate);
					} else {
						//解析自定义的bean元素,比如:<tx:annotation-driven/>
						delegate.parseCustomElement(ele);
					}
				}
			}
		} else {
			//当前采用的不是默认的命名空间
			delegate.parseCustomElement(root);
		}
	}

	/**
	 * 解析默认的元素,主要包括了 'import','alias','bean','beans'四种类型
	 *
	 * @param ele      元素
	 * @param delegate 解析器
	 */
	private void parseDefaultElement(Element ele, BeanDefinitionParserDelegate delegate) {

		if (delegate.nodeNameEquals(ele, IMPORT_ELEMENT)) {
			//处理import节点
			importBeanDefinitionResource(ele);
		} else if (delegate.nodeNameEquals(ele, ALIAS_ELEMENT)) {
			//处理别名节点
			processAliasRegistration(ele);
		} else if (delegate.nodeNameEquals(ele, BEAN_ELEMENT)) {
			//处理bean节点
			processBeanDefinition(ele, delegate);
		} else if (delegate.nodeNameEquals(ele, NESTED_BEANS_ELEMENT)) {
			//处理嵌入的beans节点
			// recurse
			doRegisterBeanDefinitions(ele);
		}
	}

	/**
	 * 将指定import元素对应的资源文件中的bean定义加载到工厂中.
	 * <p>
	 * Parse an "import" element and load the bean definitions
	 * from the given resource into the bean factory.
	 */
	protected void importBeanDefinitionResource(Element ele) {
		//获取resource属性
		String location = ele.getAttribute(RESOURCE_ATTRIBUTE);
		if (!StringUtils.hasText(location)) {
			getReaderContext().error("Resource location must not be empty", ele);
			return;
		}
		//解析系统属性,主要是处理占位符.
		// Resolve system properties: e.g. "${user.dir}"
		location = getReaderContext().getEnvironment().resolveRequiredPlaceholders(location);
		//真实资源集合
		Set<Resource> actualResources = new LinkedHashSet<>(4);
		//判断资源文件的路径是绝对的还是相对的.
		// Discover whether the location is an absolute or relative URI
		boolean absoluteLocation = false;
		try {
			absoluteLocation = ResourcePatternUtils.isUrl(location) || ResourceUtils.toURI(location).isAbsolute();
		} catch (URISyntaxException ex) {
			// cannot convert to an URI, considering the location relative
			// unless it is the well-known Spring prefix "classpath*:"
		}
		//接下来处理封别对绝对路径和相对路径进行处理.
		// Absolute or relative?
		if (absoluteLocation) {
			try {
				int importCount = getReaderContext().getReader().loadBeanDefinitions(location, actualResources);
				if (logger.isDebugEnabled()) {
					logger.debug("Imported " + importCount + " bean definitions from URL location [" + location + "]");
				}
			} catch (BeanDefinitionStoreException ex) {
				getReaderContext().error(
						"Failed to import bean definitions from URL location [" + location + "]", ele, ex);
			}
		} else {
			//如果没有URL,则将资源文件视为处于当前文件.
			// No URL -> considering resource location as relative to the current file.
			try {
				int importCount;
				//通过location创建一个相对资源对象.
				Resource relativeResource = getReaderContext().getResource().createRelative(location);
				if (relativeResource.exists()) {
					//存在加载,并放入已处理文件列表
					importCount = getReaderContext().getReader().loadBeanDefinitions(relativeResource);
					actualResources.add(relativeResource);
				} else {
					//不存在,则使用当前所在地址重新加载一次.
					String baseLocation = getReaderContext().getResource().getURL().toString();
					importCount = getReaderContext().getReader().loadBeanDefinitions(
							StringUtils.applyRelativePath(baseLocation, location), actualResources);
				}
				if (logger.isDebugEnabled()) {
					logger.debug("Imported " + importCount + " bean definitions from relative location [" + location + "]");
				}
			} catch (IOException ex) {
				getReaderContext().error("Failed to resolve current resource location", ele, ex);
			} catch (BeanDefinitionStoreException ex) {
				getReaderContext().error("Failed to import bean definitions from relative location [" + location + "]",
						ele, ex);
			}
		}
		//触发监听器.
		Resource[] actResArray = actualResources.toArray(new Resource[actualResources.size()]);
		getReaderContext().fireImportProcessed(location, actResArray, extractSource(ele));
	}

	/**
	 * 处理指定的别名元素,在注册表中注册表名.
	 * Process the given alias element, registering the alias with the registry.
	 */
	protected void processAliasRegistration(Element ele) {
		//获取name和alias属性.
		String name = ele.getAttribute(NAME_ATTRIBUTE);
		String alias = ele.getAttribute(ALIAS_ATTRIBUTE);
		//是否通过校验.
		boolean valid = true;
		if (!StringUtils.hasText(name)) {
			getReaderContext().error("Name must not be empty", ele);
			valid = false;
		}
		if (!StringUtils.hasText(alias)) {
			getReaderContext().error("Alias must not be empty", ele);
			valid = false;
		}
		if (valid) {
			try {

				//调用方法注册别名
				getReaderContext().getRegistry().registerAlias(name, alias);
			} catch (Exception ex) {
				getReaderContext().error("Failed to register alias '" + alias +
						"' for bean with name '" + name + "'", ele, ex);
			}
			getReaderContext().fireAliasRegistered(name, alias, extractSource(ele));
		}
	}

	/**
	 * 解析bean元素,并将bean定义注册到注册表中.
	 * Process the given bean element, parsing the bean definition
	 * and registering it with the registry.
	 */
	protected void processBeanDefinition(Element ele, BeanDefinitionParserDelegate delegate) {
		//通过解析器解析元素,目的是获取构成bean定义的基本元素,全限定class路径,类名,别名等值.
		BeanDefinitionHolder bdHolder = delegate.parseBeanDefinitionElement(ele);
		if (bdHolder != null) {
			bdHolder = delegate.decorateBeanDefinitionIfRequired(ele, bdHolder);
			try {
				//注册最终装饰的实例
				// Register the final decorated instance.
				BeanDefinitionReaderUtils.registerBeanDefinition(bdHolder, getReaderContext().getRegistry());
			} catch (BeanDefinitionStoreException ex) {
				getReaderContext().error("Failed to register bean definition with name '" +
						bdHolder.getBeanName() + "'", ele, ex);
			}
			// Send registration event.
			getReaderContext().fireComponentRegistered(new BeanComponentDefinition(bdHolder));
		}
	}


	/**
	 * Allow the XML to be extensible by processing any custom element types first,
	 * before we start to process the bean definitions. This method is a natural
	 * extension point for any other custom pre-processing of the XML.
	 * <p>The default implementation is empty. Subclasses can override this method to
	 * convert custom elements into standard Spring bean definitions, for example.
	 * Implementors have access to the parser's bean definition reader and the
	 * underlying XML resource, through the corresponding accessors.
	 *
	 * @see #getReaderContext()
	 */
	protected void preProcessXml(Element root) {
	}

	/**
	 * Allow the XML to be extensible by processing any custom element types last,
	 * after we finished processing the bean definitions. This method is a natural
	 * extension point for any other custom post-processing of the XML.
	 * <p>The default implementation is empty. Subclasses can override this method to
	 * convert custom elements into standard Spring bean definitions, for example.
	 * Implementors have access to the parser's bean definition reader and the
	 * underlying XML resource, through the corresponding accessors.
	 *
	 * @see #getReaderContext()
	 */
	protected void postProcessXml(Element root) {
	}

}
